/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.wms.web;

import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.fee.util.Util;
import com.jeeplus.modules.infor.entity.Goods;
import com.jeeplus.modules.infor.service.GoodsService;
import com.jeeplus.modules.infor.service.LocationService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.wms.entity.*;
import com.jeeplus.modules.wms.service.*;
import com.jeeplus.modules.wms.util.CopyUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;

/**
 * 库存查询Controller
 * @author sld
 * @version 2017-11-27
 */
@Controller
@RequestMapping(value = "${adminPath}/wms/inventory")
public class InventoryController extends BaseController {

	@Autowired
	private InventoryService inventoryService;
	@Autowired
	private LocationService locationService;
	@Autowired
    private	LnventoryMoveService lnventoryMoveService;
	@Autowired
	private InventoryAdjustmentService service;
	@Autowired
	private PickDetailedService pickDetailedService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private OutboundService outboundService;
	@Autowired
	private FrozenService frozenService;
	
	@ModelAttribute
	public Inventory get(@RequestParam(required=false) String id) {
		Inventory entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = inventoryService.get(id);
		}
		if (entity == null){
			entity = new Inventory();
		}
		return entity;
	}
	
	/**
	 * 库存查询列表页面
	 */
	@RequiresPermissions("wms:inventory:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/wms/inventoryList";
	}

	/**
	 * 报表列表页面
	 */

	@RequiresPermissions("wms:inventory:list")
	@RequestMapping(value = {"list2"})
	public String list2() {
		return "modules/wms/5/inventoryList";
	}
		/**
	 * 库存查询列表数据
	 */
	@ResponseBody
	@RequiresPermissions("wms:inventory:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Inventory inventory, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){inventory.setProjectName(pro);}
		Page<Inventory> page = inventoryService.findPage(new Page<Inventory>(request, response), inventory);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑库存查询表单页面
	 */
	@RequiresPermissions(value={"wms:inventory:view","wms:inventory:add","wms:inventory:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Inventory inventory, Model model) {
		model.addAttribute("inventory", inventory);
		return "modules/wms/inventoryForm";
	}

	/**
	 * 保存库存查询
	 */
	@ResponseBody
	@RequiresPermissions(value={"wms:inventory:add","wms:inventory:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Inventory inventory, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, inventory)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		inventoryService.save(inventory);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存库存查询成功");
		return j;
	}
	
	/**
	 * 删除库存查询
	 */
	@ResponseBody
	@RequiresPermissions("wms:inventory:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Inventory inventory, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		inventoryService.delete(inventory);
		j.setMsg("删除库存查询成功");
		return j;
	}

	@ResponseBody
	@RequestMapping("editinventory")
	public String editinventory(Inventory inventory,int sl,String i,String number){
		         if(sl!=0){
		         	PickDetailed p=new PickDetailed();
		         	p.setName(inventory.getName().getName());
					 Goods goods=goodsService.get(inventory.getName());
					int a=Integer.parseInt(goods.getTrayAmount());
					int aa=Integer.parseInt(goods.getProportion());
					 p.setAmount(sl+"");
					 p.setPamount(sl/aa+"");
					int b=sl/(a*aa);
					int c=sl%(a*aa);
		         	p.setTp(b);
		         	p.setLs(c);
		         	p.setPro(UserUtils.getUseroffice());
                    p.setProductAddress(inventory.getPlace());
		         	p.setCode(inventory.getCode());
		         	p.setNumber(number);
		         	p.setLocation(inventory.getLocation().getName());
					 Outbound o=outboundService.get(i);
					 p.setWorkType(o.getWorkType());
					 p.setShippingOrder(o.getShipmentNumbers());
		         	p.setOutbount(i);
		         	p.setNo(o.getUnitName());
		         	p.setBach(inventory.getBatch());
		         	p.setPickDate(new Date());


                if(Integer.parseInt(inventory.getUsable())==sl&&inventory.getAllocation().equals("0")){
                	p.setZq(sl+"");
                	p.setZh("0");
						inventoryService.delete(inventory);
				}else{
                	  p.setZq(inventory.getInventoryNumber());
                      int s=Integer.parseInt(inventory.getInventoryNumber())-sl;
                      int s1=Integer.parseInt(inventory.getUsable())-sl;
                      inventory.setUsable(s1+"");
                      inventory.setInventoryNumber(s+"");
                      inventoryService.save(inventory);
                      p.setZh(inventory.getInventoryNumber());
				}
					 pickDetailedService.save(p);
		         }
				return "";
	}


	/**
	 * 批量删除库存查询
	 */
	@ResponseBody
	@RequiresPermissions("wms:inventory:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			inventoryService.delete(inventoryService.get(id));
		}
		j.setMsg("删除库存查询成功");
		return j;
	}

	@ResponseBody
	@RequestMapping("detil")
	public  String detil(String i){
		Gson g=new Gson();
		return g.toJson(inventoryService.get(i)).toString();
	}
	@ResponseBody
	@RequestMapping("up")
	public  String up(String i,String amount,String reson){
		Inventory in=inventoryService.get(i);
		InventoryAdjustment m=new InventoryAdjustment();
		m.setBatch(in.getBatch());
		m.setDate(in.getData());
		m.setReson(reson);
		m.setLocation(in.getLocation());
		m.setShipperCode(in.getShipperCode());
		m.setMaterialCode(in.getCode());
		m.setMaterialName(in.getName().getName());
		m.setOriginal(in.getUsable());
		m.setOperator(UserUtils.getUser());
		m.setOperationTime(new Date());
		m.setInboundDate(in.getInboundDate());
		m.setLimitedPeriod(in.getLimitedPeriod());
		m.setProjectName(in.getProjectName());
		if(Integer.parseInt(in.getUsable())>Integer.parseInt(amount)){
			m.setDeducting((Integer.parseInt(in.getUsable())-Integer.parseInt(amount))+"");
		}else{
			m.setIncrease((Integer.parseInt(amount)-Integer.parseInt(in.getUsable()))+"");
		}
		service.save(m);
		if(Integer.parseInt(amount)==0&&Integer.parseInt(in.getAllocation())==0){
			inventoryService.delete(in);
		}else{
			String w="0";
			if(in.getAllocation()!=null||in.getAllocation()!=""){
				 w=in.getAllocation();
			}
       int a=Integer.parseInt(amount)+Integer.parseInt(w);
			in.setUsable(amount);
			in.setInventoryNumber(a+"");
			inventoryService.save(in);
		}
		return "";
	}
	@ResponseBody
	@RequestMapping("move")
	public  String move(String i,String location,String amount){
        Inventory inventory=inventoryService.get(i);
		LnventoryMove move=new LnventoryMove();
		move.setUsable(inventory.getUsable());
		move.setMaterialName(inventory.getName().getName());
		move.setStatus(inventory.getStatus());
		move.setUsableStandard(inventory.getUsable());
		move.setLocation(inventory.getLocation());
		move.setToLocation(locationService.get(location));
		move.setBatch(inventory.getBatch());
		move.setBatchProperty(inventory.getBatchProperty());
		move.setDate(inventory.getData());
		move.setMoveQuantity(amount);
		move.setExisting(inventory.getExisting());
		move.setExistingStandard(inventory.getExistingStandard());
		move.setExternalNumber(inventory.getExternalNumber());
		move.setLimitedPeriod(inventory.getLimitedPeriod());
		move.setInboundDate(inventory.getInboundDate());
		move.setShipperCode(inventory.getShipperCode());
		move.setPackagingCode(inventory.getPackaging());
		move.setMaterialCode(inventory.getCode());
		move.setQuantityAllotted(inventory.getAvailableQuantity());
		move.setOperatDate(new Date());
		move.setOperater(UserUtils.getUser());
		move.setProjectName(inventory.getProjectName());
		lnventoryMoveService.save(move);

		Inventory in=new Inventory();
		in= (Inventory) CopyUtil.Copy(in,inventory,false);
        String d=inventory.getUsable();
        String d0=inventory.getInventoryNumber();
		String w="0";
		if(in.getAllocation()!=null||in.getAllocation()!=""){
			w=in.getAllocation();
		}
        if(Integer.parseInt(d)>	Integer.parseInt(amount)){
			inventory.setUsable((Integer.parseInt(d)-Integer.parseInt(amount))+"");
			inventory.setInventoryNumber((Integer.parseInt(d0)-Integer.parseInt(amount))+"");
			inventoryService.save(inventory);
		}else{
        	if(Integer.parseInt(w)!=0){
				inventory.setUsable("0");
				inventory.setInventoryNumber((Integer.parseInt(d0)-Integer.parseInt(amount))+"");
				inventoryService.save(inventory);
			}else{
        	inventoryService.delete(inventory);
		}}
		in.setLocation(locationService.get(location));
        List<Inventory> list=inventoryService.findList(in);
        if(list==null||list.size()<1){
			in.setUsable(amount);
			in.setAllocation("0");
			in.setPicking("0");
			in.setLsPicking("0");
			in.setInventoryNumber(amount);
			inventoryService.save(in);
		}else{
        	Inventory inv=list.get(0);
        	String f=list.get(0).getUsable();
			String fd=list.get(0).getInventoryNumber();
			inv.setUsable((Integer.parseInt(f)+Integer.parseInt(amount))+"");
			inv.setInventoryNumber((Integer.parseInt(fd)+Integer.parseInt(amount))+"");
			inventoryService.save(inv);
		}

		return "";
	}
	/**
	 * 导出excel文件
	 */
	@ResponseBody
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String  exportFile(Inventory inventory,String ids, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes,Model model) throws IOException {
		// 1.创建一个workbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 2.在workbook中添加一个sheet，对应Excel中的一个sheet
		HSSFSheet sheet = wb.createSheet("XXX表");
		// 3.在sheet中添加表头第0行，老版本poi对excel行数列数有限制short
		HSSFRow row = sheet.createRow((int) 0);
		// 4.创建单元格，设置值表头，设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		// 居中格式
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

		// 设置表头
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("货位");
		cell.setCellStyle(style);

		cell = row.createCell(1);
		cell.setCellValue("物料编码");
		cell.setCellStyle(style);

		cell = row.createCell(2);
		cell.setCellValue("物料名称");
		cell.setCellStyle(style);

		cell = row.createCell(3);
		cell.setCellValue("货主");
		cell.setCellStyle(style);

		cell = row.createCell(4);
		cell.setCellValue("库存量");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("可用量");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("冻结量");
		cell.setCellStyle(style);
		cell = row.createCell(7);
		cell.setCellValue("批次");
		cell.setCellStyle(style);
		List<Inventory> lists=new ArrayList<>();
		if(ids==null||ids==""||ids=="undifind"){
			lists=inventoryService.findList(new Inventory());
		}else{
			String[] i=ids.split(",");
			for(String id:i){
				lists.add(inventoryService.get(id));
			}
		}

// 循环将数据写入Excel
		for (int i = 0; i < lists.size(); i++) {
			row = sheet.createRow((int) i + 1);
			// 创建单元格，设置值
				Inventory in=lists.get(i);
				in=inventoryService.get(in.getId());
			row.createCell(0).setCellValue(in.getLocation().getName());
			row.createCell(1).setCellValue(in.getCode());
			row.createCell(2).setCellValue(in.getName().getName());
			row.createCell(3).setCellValue(in.getShipperCode());
			row.createCell(4).setCellValue(in.getInventoryNumber());
				row.createCell(5).setCellValue(in.getUsable());
			row.createCell(6).setCellValue(in.getAllocation());
			row.createCell(7).setCellValue(in.getBatch());
		}

		FileOutputStream out =new FileOutputStream("E:/库存.xls");
		wb.write(out);
		out.close();
//		String fileName = "XXX表";
//		ByteArrayOutputStream os = new ByteArrayOutputStream();
//		wb.write(os);
//		byte[] content = os.toByteArray();
//		InputStream is = new ByteArrayInputStream(content);
//		// 设置response参数，可以打开下载页面
//		res.reset();
//		res.setContentType("application/vnd.ms-excel;charset=utf-8");
//		res.setHeader("Content-Disposition", "attachment;filename="
//				+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
//		ServletOutputStream out = res.getOutputStream();
//		BufferedInputStream bis = null;
//		BufferedOutputStream bos = null;
//
//		try {
//			bis = new BufferedInputStream(is);
//			bos = new BufferedOutputStream(out);
//			byte[] buff = new byte[2048];
//			int bytesRead;
//			// Simple read/write loop.
//			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
//				bos.write(buff, 0, bytesRead);
//			}
//		} catch (Exception e) {
//			// TODO: handle exception
//			e.printStackTrace();
//		} finally {
//			if (bis != null)
//				bis.close();
//			if (bos != null)
//				bos.close();
//		}
			return "";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("wms:inventory:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Inventory> list = ei.getDataList(Inventory.class);
			for (Inventory inventory : list){
				try{inventory.setProjectName(UserUtils.getUseroffice());
					Goods g=new Goods();
					g.setCode(inventory.getCode());
					g.setProject(UserUtils.getUseroffice());
					List<Goods> l=goodsService.findList(g);
					if(l!=null&&l.size()>0){g=l.get(0);
						inventory.setName(g);
					}
					inventoryService.save(inventory);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条库存查询记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条库存查询记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入库存查询失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/wms/inventory/?repage";
    }
	
	/**
	 * 下载导入库存查询数据模板
	 */
	@RequiresPermissions("wms:inventory:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "库存查询数据导入模板.xlsx";
    		List<Inventory> list = Lists.newArrayList(); 
    		new ExportExcel("库存查询数据", Inventory.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/wms/inventory/?repage";
    }


	@RequestMapping("dj")
	@ResponseBody
    public String dj(String i,String amount,String reson){
		Inventory in=inventoryService.get(i);
		String b=Integer.parseInt(in.getAllocation())+Integer.parseInt(amount)+"";
		in.setAllocation(b);
		String a=Integer.parseInt(in.getUsable())-Integer.parseInt(amount)+"";
		in.setUsable(a);
		inventoryService.save(in);
		Frozen f=new Frozen();
		f.setCode(in.getCode());
		f.setName(in.getName().getName());
		f.setLocation(in.getLocation().getName());
		f.setHzdm(in.getShipperCode());
		f.setNumber(amount);
		f.setReson(reson);
		f.setDate(new Date());
		f.setPerson(UserUtils.getUserName());
		f.setPro(in.getProjectName());
		frozenService.save(f);
		return "";
	}

	@RequestMapping("qx")
	@ResponseBody
	public String qx(String i,String amount){
		Inventory in=inventoryService.get(i);
		String b=Integer.parseInt(in.getAllocation())-Integer.parseInt(amount)+"";
		in.setAllocation(b);
		String a=Integer.parseInt(in.getUsable())+Integer.parseInt(amount)+"";
		in.setUsable(a);
		inventoryService.save(in);
		return "";
	}
}